!function () {
    var lastData = {},
        areaIndex = 0;
    var buyInsurance = window.WEBBASE.extend({
        init: function () {//初始化

            // 地址选择地区
            this.selectArea('.J_get-area0');
            //计算价格
            this.calcInsurancePice();
        },
        events: {
            "#J_add-the-insured-info click": "addTheInsuredInfo",//添加新被保险人及标的信息
            ".J_the-insured-del click": "theInsuredDel",//删除新被保险人及标的信息
            ".J_add-fileupload change": "fileuploadFn",//上传身份证图片
            ".J_delete-pic click": "deletePic",//删除上传图片
            "#J_buy-now click": "buyNow",//立即购买
            "#J_read-terms click": "readTerms",//阅读条款
            ".J_the-insured-select change": "theInsuredSelectChange",//与投保人关系选择 选择本人后去上面投保人已经输入的值
        },
        /**
         * 添加新被保险人及标的信息
         */
        addTheInsuredInfo: function () {
            if ($('.the-insured-info').length >= 10) {
                Tools.msg('最多可以添加10个被保险人及标的信息!');
                return;
            }
            areaIndex++;
            var unitPrice = $('#J_unit-price').val();//单价
            var html =
                '<div class="insurance-item-com the-insured-info">' +
                '<p class="item-tit">' +
                '<span class="tit-txt">被保险人及标的信息</span>' +
                '<span class="item-del J_the-insured-del">删除</span>' +
                '</p>' +
                '<div class="item-cont">' +
                '<p class="item-list applicant-relation">' +
                '<span class="list-txt">与投保人关系</span>' +
                '<span class="list-r">' +
                '<select name="" id="" class="relation-select J_the-insured-select">' +
                '<option value="0">请选择</option>' +
                '<option value="1">本人</option>' +
                '<option value="2">孩子</option>' +
                '</select>' +
                '</span>' +
                '</p>' +
                '<p class="item-list">' +
                '<span class="list-txt">姓名：</span>' +
                '<span class="list-r">' +
                '<input class="list-input J_the-insured-name" type="text" placeholder="输入真实姓名">' +
                '</span>' +
                '</p>' +
                '<p class="item-list">' +
                '<span class="list-txt">身份证：</span>' +
                '<span class="list-r">' +
                '<input class="list-input J_the-insured-ID-number" type="text" placeholder="输入身份证号">' +
                '</span>' +
                '</p>' +
                '<div class="item-list card-info">' +

                '<div class="photo">' +
                '<div class="add-photo">' +
                '<a class="add-photo-icon" href="javascript:void(0)"></a>' +
                '<input type="file" class="J_add-fileupload">' +
                '</div>' +
                '</div>' +
                '<p class="tips">注：请上传被保险人身份证正反面(共两张)</p>' +

                '</div>' +
                '<p class="item-list">' +
                '<span class="list-txt">项目地址(并网地点房屋地址)：</span>' +
                '<span class="list-r">' +
                '<input class="J_save-input J_sel-area J_get-area' + areaIndex + '" name="get-area" type="text" placeholder="省份 城市 区县">' +
                '</span>' +
                '</p>' +
                '<p class="item-list">' +
                '<span class="list-r">' +
                '<input style="text-align: left;" class="list-input J_the-insured-detail-address" type="text" placeholder="请输入电站详细地址，具体到门牌号">' +
                '</span>' +
                '</p>' +
                '<p class="item-list">' +
                '<span class="list-txt">造价总额：</span>' +
                '<span class="list-r">' +
                '<input class="list-input J_the-insured-total-cost" type="text" placeholder="请填写真实金额以便计算保险金额(元)">' +
                '</span>' +
                '</p>' +
                '<p class="item-list">' +
                '<span class="list-txt">保障期限： </span>' +
                '<span class="list-r">' +
                '<input class="list-input J_the-insured-date" value="一年" readonly type="text" placeholder="一年">' +
                '</span>' +
                '</p>' +
                '<p class="item-list applicant-relation">' +
                '<span class="list-txt">保险套餐：</span>' +
                '<span class="list-r">' +
                '<select name="" id="" class="relation-select J_the-insured-insurance-set-meal">' +
                '<option value="0">请选择</option>' +
                '<option value="1">综合险+第三方责任险</option>' +
                '<option value="2">综合险+第三</option>' +
                '</select>' +
                '</span>' +
                '</p>' +
                '<p class="item-list insurance-price">' +
                '<span class="list-txt">保险金额：</span>' +
                '<span class="list-r">' +
                '<i class="price"><span class="J_the-insured-price">' + unitPrice + '</span>元</i>' +
                '</span>' +
                '</p>' +
                '</div>' +
                '</div>';
            $('#J_the-insured-info-out').append(html);
            this.selectArea('.J_get-area' + areaIndex);
            //计算价格
            this.calcInsurancePice();
        },
        /**
         * 删除新被保险人及标的信息
         * @param e
         */
        theInsuredDel: function (e) {
            var self = $(e.currentTarget),
                $theInsuredInfo = self.parents('.the-insured-info');
            $theInsuredInfo.remove();
            //计算价格
            this.calcInsurancePice();
        },
        /**
         * 上传com fn
         * @param ele
         * @param callback
         * @param config
         * @returns {boolean}
         */
        fileuploadCom: function (ele, callback, config) {
            var $canvas = $('#J_canvas');
            if (!$canvas.length > 0) {
                $('body').append('<canvas id="J_canvas" style="display: none;"></canvas>');
                $canvas = $('#J_canvas');
            }
            config = {
                // configCanvas: config.canvas || $canvas,//画布对象
                compressHeight: config.compressHeight || 480//压缩的高度
            };
            var file = ele.currentTarget.files[0],
                oUrl = URL,
                url = oUrl.createObjectURL(file);

            if (!/image\/\w+/.test(file.type)) {
                Tools.msg('请选择图片上传!');
                return false;
            }

            var Orientation = null;
            //获取照片方向角属性，用户旋转控制
            EXIF.getData(file, function () {
                // Tools.msg(EXIF.pretty(this));
                EXIF.getAllTags(this);
                //Tools.msg(EXIF.getTag(this, 'Orientation'));
                Orientation = EXIF.getTag(this, 'Orientation');
                //return;
            });
            var newImg = new Image();
            newImg.onload = function (e) {//图片加载成功回调函数
                //对图片旋转处理
                var rotateImg = function (img, direction, canvas, config) {
                    //最小与最大旋转方向，图片旋转4次后回到原方向
                    var min_step = 0;
                    var max_step = 3;
                    //var img = document.getElementById(pid);
                    if (img == null)return;
                    //img的高度和宽度不能在img元素隐藏后获取，否则会出错
                    var height = img.height;
                    var width = img.width;

                    //压缩宽高
                    var scale = height / width,
                        compressHeight = parseInt(config.compressHeight),//高
                        compressWidth = parseInt(compressHeight / scale);//宽，等比压缩
                    //var step = img.getAttribute('step');
                    var step = 2;
                    if (step == null) {
                        step = min_step;
                    }
                    if (direction == 'right') {
                        step++;
                        //旋转到原位置，即超过最大值
                        step > max_step && (step = min_step);
                    } else {
                        step--;
                        step < min_step && (step = max_step);
                    }
                    //旋转角度以弧度值为参数
                    var degree = step * 90 * Math.PI / 180;
                    canvas = canvas[0];//转化为dom对象
                    var ctx = canvas.getContext('2d');
                    // context.drawImage(img,x,y,width,height); //在画布上定位图像，并规定图像的宽度和高度
                    // console.log('step is:' + step)
                    switch (step) {
                        case 0:
                            canvas.width = compressWidth;
                            canvas.height = compressHeight;
                            ctx.drawImage(img, 0, 0, compressWidth, compressHeight);
                            break;
                        case 1:
                            canvas.width = compressHeight;
                            canvas.height = compressWidth;
                            ctx.rotate(degree);
                            ctx.drawImage(img, 0, -compressHeight, compressWidth, compressHeight);
                            break;
                        case 2:
                            canvas.width = compressWidth;
                            canvas.height = compressHeight;
                            ctx.rotate(degree);
                            ctx.drawImage(img, -compressWidth, -height, compressWidth, compressHeight);
                            break;
                        case 3:
                            canvas.width = compressHeight;
                            canvas.height = compressWidth;
                            ctx.rotate(degree);
                            ctx.drawImage(img, -compressWidth, 0, compressWidth, compressHeight);
                            break;
                    }

                };

                //如果方向角不为1，都需要进行旋转
                if (Orientation != "" && Orientation != 1 && Orientation != undefined) {//修复ios 三星 等手机或拍摄角度有问题的图片
                    switch (Orientation) {
                        case 6://需要顺时针（向左）90度旋转
                            rotateImg(this, 'left', $canvas, config);
                            break;
                        case 8://需要逆时针（向右）90度旋转
                            rotateImg(this, 'right', $canvas, config);
                            break;
                        case 3://需要180度旋转
                            rotateImg(this, 'right', $canvas, config);//转两次
                            rotateImg(this, 'right', $canvas, config);
                            break;
                    }
                } else {//角为1 (正常拍摄角度图片 ios，android)
                    // 生成比例
                    var width = newImg.width, height = newImg.height, scale = height / width;
                    height = parseInt(config.compressHeight);//高
                    width = parseInt(height / scale);//宽，等比压缩
                    // 生成canvas （主要用来压缩图片） $canvas[0] 把jq对象转成dom对象
                    var ctx = $canvas[0].getContext('2d');//getContext()方法返回一个用于在画布上绘图的环境
                    $canvas.attr({
                        width: width,
                        height: height
                    });
                    ctx.drawImage(newImg, 0, 0, width, height);//drawImage() 方法在画布上绘制图像、画布或视频。 也能够绘制图像的某些部分，以及/或者增加或减少图像的尺寸。  context.drawImage(img,sx,sy,swidth,sheight,x,y,width,height);
                    //mg	规定要使用的图像、画布或视频。
                    //sx	可选。开始剪切的 x 坐标位置。
                    //sy	可选。开始剪切的 y 坐标位置。
                    //swidth	可选。被剪切图像的宽度。
                    //sheight	可选。被剪切图像的高度。
                }

                var base64 = $canvas[0].toDataURL('image/jpeg', 0.5);//HTMLCanvasElement.toDataURL() 方法返回一个包含图片展示的 data URI 。
                //canvas.toDataURL(type, encoderOptions); encoderOptions：可以从 0 到 1 的区间内选择图片的质量
                var imgData = new FormData();//用FormData 而不是直接传base64 会使传给程序的数据减少
                imgData.append('file', base64.substr(23));

                $.ajax({
                    // url: window.requestUrlAudition + '/api/activity/audition/uploadImage/V4',
                    url: '',
                    type: 'POST',
                    async: false,
                    data: imgData,
                    processData: false,  // 告诉jQuery不要去处理发送的数据
                    contentType: false // 告诉jQuery不要去设置Content-Type请求头
                }).done(function (res) {
                    res = {
                        "code": 1,
                        "msg": "成功！",
                        "interfaceIdentity": null,
                        // "entity": {"value": "http://192.168.68.2:9002/xmResources/productImages/activity/audition4/1477374940550_34.jpg"}
                        "entity": {"value": url}//这里后端提供上传成功后的图片地址
                    };
                    typeof  callback == 'function' && callback(res);
                }).always(function () {
                    // $(ele.currentTarget).val('')
                    // uploadPicUrl = $(ele.currentTarget).val();
                }).fail(function () {
                    // $(ele.currentTarget).val('')
                });
                // ;
            };
            newImg.onerror = function () {
                Tools.msg('图片已损坏，请选择其他图片!');
                // return;
            };
            newImg.src = url;
        },
        /**
         *上传图片
         * @param e
         * @returns {boolean}
         */
        showFileuploadChange: function (e) {

            var that = this,
                photolist = $("#photolist");
            var self = $(e.currentTarget),
                $photoList = self.parent('.add-photo').siblings('.photo-list');
            if ($photoList.length == 2) {
                Tools.msg('您已上传好2张照片,如果需修改，请删除重试!');
                return;
            }
            var fileuploadComCallback = function (res) {//图片上传回调
                    if (parseInt(res.code) === 1) {
                        that.addImageShow(self, res.entity.value);//res.entity.value为上传后的图片路径
                    }
                    else {
                        Tools.msg(res.msg);
                    }
                },
                config = {
                    // configCanvas: $('#canvas'),//画布对象
                    compressHeight: 480//压缩的高度
                };
            //图片上传
            that.fileuploadCom(e, fileuploadComCallback, config);
        },
        /**
         * 上传图片展示
         * @param self
         * @param src
         */
        addImageShow: function (self, src) {
            var $addPhoto = self.parents(".add-photo");
            var str =
                '<div class="photo-list J_photo-list">' +
                '<img src="' + src + '" alt="">' +
                '<input name="photoUrl" type="hidden" value="' + src + '"/>' +
                '<div class="delete"></div><i class="delete-i J_delete-pic"></i></div>';
            $addPhoto.before(str);
        },
        /**
         * 选择收货地区
         */
        selectArea: function (ele) {
            var selectArea = new MobileSelectArea();
            selectArea.init({
                trigger: ele,//  触发弹窗的DOM元素 ，可以是input或其他
                // value: $('.J_get-area-hide').val(),// 初始值,
                data: '../js/city_data.json',
                position: "bottom",
                callback: function (res) {
                    //保存选择地区
                    // $('.J_get-area').keyup();
                }
            });
        },
        /**
         * 上传身份证图片
         * @param e
         */
        fileuploadFn: function (e) {
            if (!e) {
                return;
            }
            this.showFileuploadChange(e)
        },
        /**
         * 删除上传图片
         * @param e
         */
        deletePic: function (e) {
            var self = $(e.currentTarget);
            self.parents('.photo-list').siblings('.add-photo').find('.J_add-fileupload').val('');
            self.parents('.photo-list').remove();
        },
        /**
         * 身份证号
         * @param str
         * @returns {boolean}
         */
        isCardID: function (str) {
            var isOk = true,
                d = new Date(),
                aCity = {
                    11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林",
                    23: "黑龙江", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西",
                    37: "山东", 41: "河南", 42: "湖北", 43: "湖南", 44: "广东", 45: "广西", 46: "海南",
                    50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏", 61: "陕西", 62: "甘肃",
                    63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外"
                };
            //验证长度
            if (!/^\d{17}(\d|x|X)$/.test(str)) {
                isOk = false;
            }
            str = str.replace(/x$/i, "a");
            //验证地区
            if (aCity[parseInt(str.substr(0, 2))] == null) {
                isOk = false;
            }
            //验证年份
            var iyear = Number(str.substr(6, 4)), curYear = Number(d.getFullYear());
            if (iyear < 1900 || iyear > curYear) {
                isOk = false;
            }
            //验证月份
            var imonth = Number(str.substr(10, 2)), curMonth = Number(d.getMonth()) + 1;
            if (imonth < 1 || imonth > 12) {
                isOk = false;
            }
            if (iyear == curYear && imonth > curMonth) {
                isOk = false;
            }
            //验证天数
            var iday = Number(str.substr(12, 2)), curDay = Number(d.getDate());
            //大月
            if ((imonth == 1 || imonth == 3 || imonth == 5 || imonth == 7 || imonth == 8 || imonth == 10 || imonth == 12) && (iday < 1 || iday > 31)) {
                isOk = false;
            }
            //二月
            var isLeapYear = ((iyear % 4) == 0) && ((iyear % 100) != 0) || ((iyear % 400) == 0);//闰年
            if (imonth == 2 && !isLeapYear && (iday < 1 || iday > 28)) {
                isOk = false;
            }
            if (imonth == 2 && isLeapYear && (iday < 1 || iday > 29)) {
                isOk = false;
            }
            if (imonth == 2 && (iday < 1 || iday > 29)) {
                isOk = false;
            }
            //小月
            if ((imonth == 4 || imonth == 6 || imonth == 9 || imonth == 11 ) && (iday < 1 || iday > 30)) {
                isOk = false;
            }
            //是否大于当前日期
            if (iyear == curYear && imonth == curMonth && iday > curDay) {
                isOk = false;
            }
            return isOk;
        },
        /**
         * 提交表单数据验证
         */
        formVerify: function () {
            var $applicantNameVal = $('#J_applicant-name').val();
            if (!$applicantNameVal) {
                Tools.msg('请输入真实姓名！');
                return false;
            }
            var $applicantIDNumberVal = $('#J_applicant-ID-number').val();
            if (!$applicantIDNumberVal) {
                Tools.msg('请输入身份证号！');
                return false;
            }
            var numRe = /^\d*$/;
            if (!this.isCardID($applicantIDNumberVal)) {
                Tools.msg('请输入正确的身份证号！');
                return false;
            }
            var $applicantTelVal = $('#J_applicant-tel').val();
            if (!$applicantTelVal) {
                Tools.msg('请输入手机号！');
                return false;
            }
            var telRe = /^(86)?1[3,4,5,7,8]\d{9}$/;
            if (!telRe.test($applicantTelVal)) {
                Tools.msg('请正确电话号码！');
                return false;
            }

            //被保险人及标的信息验证
            var $theInsuredInfo = $('#J_the-insured-info-out').find('.the-insured-info'),
                $theInsuredInfoLen = $theInsuredInfo.length;
            if ($theInsuredInfoLen == 0) {
                Tools.msg('请添加被保险人及标的信息！');
                return false;
            }
            var theInsuredInfoArr = [];
            for (var i = 0; i < $theInsuredInfoLen; i++) {

                var $theInsuredSelectVal = $theInsuredInfo.eq(i).find('.J_the-insured-select').val();
                if ($theInsuredSelectVal == '0') {
                    Tools.msg('请选择与投保人关系！');
                    return false;
                }
                var $theInsuredNameVal = $theInsuredInfo.eq(i).find('.J_the-insured-name').val();
                if (!$theInsuredNameVal) {
                    Tools.msg('请输入真实姓名！');
                    return false;
                }
                var $theInsuredIDNumberVal = $theInsuredInfo.eq(i).find('.J_the-insured-ID-number').val();
                if (!$theInsuredIDNumberVal) {
                    Tools.msg('请输入身份证号！');
                    return false;
                }
                if (!this.isCardID($theInsuredIDNumberVal)) {
                    Tools.msg('请输入正确的身份证号！');
                    return false;
                }
                var $photoList = $theInsuredInfo.eq(i).find('.J_photo-list'),
                    $photoListLen = $photoList.length;
                if ($photoListLen == 0 || $photoListLen < 2) {
                    Tools.msg('请上传被保险人身份证正反面(共两张)！');
                    return false;
                }
                var $selAreaVal = $theInsuredInfo.eq(i).find('.J_sel-area').val();
                if (!$selAreaVal) {
                    Tools.msg('请选择项目地址！');
                    return false;
                }
                var $theInsuredDetailAddressVal = $theInsuredInfo.eq(i).find('.J_the-insured-detail-address').val();
                if (!$theInsuredDetailAddressVal) {
                    Tools.msg('请输入电站详细地址，具体到门牌号！');
                    return false;
                }
                var $theInsuredTotalCostVal = $theInsuredInfo.eq(i).find('.J_the-insured-total-cost').val();
                if (!$theInsuredTotalCostVal) {
                    Tools.msg('请填写真实金额以便计算保险金额！');
                    return false;
                }
                if (!numRe.test($theInsuredTotalCostVal)) {
                    Tools.msg('请填写正确的保险金额！');
                    return false;
                }
                var $theInsuredInsuranceSetMealVal = $theInsuredInfo.eq(i).find('.J_the-insured-insurance-set-meal').val();
                if ($theInsuredInsuranceSetMealVal == '0') {
                    Tools.msg('请选择保险套餐！');
                    return false;
                }

                //身份证图片
                var photoListStr = '';
                for (var j = 0; j < $photoListLen; j++) {
                    photoListStr += $photoList.eq(j).find('img').attr('src') + ','
                }
                photoListStr = photoListStr.substr(0, photoListStr.length - 1)
                var obj = {
                    theInsuredSelect: $theInsuredSelectVal,//与投保人关系
                    theInsuredName: $theInsuredNameVal,//真实姓名
                    theInsuredIDNumber: $theInsuredIDNumberVal,//身份证号
                    photoList: photoListStr,//身份证正反面
                    selArea: $selAreaVal,//项目地址
                    theInsuredDetailAddress: $theInsuredDetailAddressVal,//电站详细地址，具体到门牌号
                    theInsuredTotalCost: $theInsuredTotalCostVal,//真实金额以便计算保险金额
                    theInsuredInsuranceSetMeal: $theInsuredInsuranceSetMealVal,//请选择保险套餐
                };
                theInsuredInfoArr.push(obj)

            }

            var $eMail = $('#J_e-mail').val();
            if (!$eMail) {
                Tools.msg('请填写邮箱！');
                return false;
            }
            var eMailRe = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
            if (!eMailRe.test($eMail)) {
                Tools.msg('请填写正确的邮箱地址！');
                return false;
            }
            var $ReadTerms = $('#J_read-terms');
            if (!$ReadTerms.hasClass('cur')) {
                Tools.msg('请阅读并同意《投保须知》和《保险条款》！');
                return false;
            }

            lastData.formData = {
                applicantName: $applicantNameVal,//投保人真实姓名
                applicantIDNumber: $applicantIDNumberVal,//投保人身份证号
                theInsuredInfo: theInsuredInfoArr,//被保险人及标的信息数组
                applicantTel: $applicantTelVal,//投保人手机号
                eMail: $eMail,//投保e-mail
            };
            // console.log(lastData.formData, 'lastData.formData')
            return true;

        },
        /**
         * 立即购买
         */
        buyNow: function () {
            if (!this.formVerify()) {
                return;
            }
            $.ajax({
                url: '',
                data: lastData.formData,
                dataType: 'json',
                type: 'POST',
                success: function (res) {
                    Tools.msg(res.msg);
                },
                error: function (res) {
                    Tools.msg(res.msg);
                }
            })
        },
        /**
         * 阅读条款
         * @param e
         */
        readTerms: function (e) {
            var self = $(e.currentTarget);
            if (self.hasClass('cur')) {
                self.removeClass('cur');
            } else {
                self.addClass('cur');
            }
        },
        /**
         *与投保人关系选择 选择本人后去上面投保人已经输入的值
         * @param e
         */
        theInsuredSelectChange: function (e) {
            var self = $(e.currentTarget),
                $applicantNameVal = $('#J_applicant-name').val(),
                $applicantIDNumber = $('#J_applicant-ID-number').val();
            //选择的是本人
            if (self.val() == 1 && (!$applicantNameVal || !$applicantNameVal)) {
                Tools.msg('请先输入投保人信息！');
                self.val(0);
                return;
            }
            var $theInsuredName = self.parents('.applicant-relation').siblings('.item-list').find('.J_the-insured-name'),
                $theInsuredIDNumber = self.parents('.applicant-relation').siblings('.item-list').find('.J_the-insured-ID-number');
            //选择的是非本人
            if (self.val() != 1) {
                $theInsuredName.val('');
                $theInsuredIDNumber.val('');
                return;
            }
            $theInsuredName.val($applicantNameVal);
            $theInsuredIDNumber.val($applicantIDNumber);

        },
        /**
         * 计算保险总价格
         */
        calcInsurancePice: function () {
            var $insurancePrice = $('#J_unit-price').val(),//保险单价格
                $theInsuredPrice = $('.J_the-insured-price');//保险价格
            $theInsuredPrice.text($insurancePrice)
            $('.J_insurance-total-price').text($insurancePrice * $theInsuredPrice.length)
        }
    });

    buyInsurance.init();
}();